<template>
    <div class="demo-block">
      <el-autocomplete
        v-model="state.select"
        :fetch-suggestions="querySearch"
        clearable
        class="w-50"
        placeholder="Please Input"
        @select="handleSelect"
        @clear="clear"
      />
    </div>

    <div class="ca" v-for="(v, k) in state.wordsMap" :key="k">
        <h1>{{ k }}</h1>
        <div class="words">
            <div v-for="(word, index) in v" :key="index" class="word" @click="drawerClick(word)">
                {{ word }}
            </div>
        </div>
    </div>

    <el-drawer v-model="drawer" :with-header="false" size="800px">
        <words-detail :word="state.click" :key="state.click"></words-detail>
    </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { getWords } from '../api/words';
import type { WordsResponseData } from '../api/words';
import WordsDetail from '@/components/WordsDetail.vue';

const drawer = ref(false)

const state = reactive({
    select: '',
    click: '',
    rawWords: []  as string[],
    words: []  as string[],
    wordsMap: {} as Record<string, string[]>
});

getWords().then((res : WordsResponseData) => {
    state.rawWords = res.data;
    state.words = res.data;
    built();
});

const drawerClick = (word : string) => {
    drawer.value = true;
    state.click = word;
};

const built = (words : string[] = state.rawWords) => {
    state.wordsMap  = words.reduce((acc : Record<string, string[]>, word : string) => {
    let firstLetter = word[0].toLowerCase(); // 获取首字母并转为小写
    if (!acc[firstLetter]) {
        acc[firstLetter] = []; // 如果该字母不存在，初始化一个空数组
    }
    acc[firstLetter].push(word); // 将单词添加到对应的字母分组
    return acc;
    }, {});
};

const querySearch = (queryString: string, cb: any) => {
    let ret : { value: string }[] = []

    if (!queryString) {
        state.words.forEach(item => {
            ret.push({ value: item });
        })
    } else {
        state.words.forEach(item => {
            if (item.includes(queryString)) {
                ret.push({ value: item });
            }
        });
    }
    built(ret.map(item => item.value))
    cb(ret)
}

const clear = () => {
    built()
}
const handleSelect = (item: Record<string, any>) => {
    built([item.value]);
}
</script>

<style scoped>
.words {
    display: flex;
    flex-wrap: wrap;
}
.word {
    font-size: 20px;
    border: 1px solid black;
    width: 200px;
    height: 150px;
    margin: 10px;
    text-align: center;
}
</style>